package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.constant.RouterConstant;
import com.qk.properties.JwtProperties;
import com.qk.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
public class TokenFilter implements Filter {

     private final JwtProperties jwtProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (ObjectUtil.equals(request.getRequestURI(), RouterConstant.USER_LOGIN)) {
            log.info("获取发送请求方的ip,{}", request.getRemoteAddr());
            log.info("获取发送请求方的主机名,{}", request.getRemoteHost());
            chain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(RouterConstant.TOKEN_HEADER_NAME);
        if (token == null || token.isEmpty()) {
            log.info("请求头中没有 token, 拒绝访问, 401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(jwtProperties.getSecretKey(), token);
            System.out.println( claims);
        } catch (Exception e) {
            // 捕获解析 token 异常，返回 401 错误
            log.info("解析 token 出错, 拒绝访问, 401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("token 正确, 继续执行后续过滤器或请求处理");
        chain.doFilter(request, response);
    }
}